import type { UserRole } from "../auth/auth";
import { fromError, initAxios, type ApiResponse } from "../common";

const client = initAxios();

export type NovelListResponse = {
  total: number;
  novels: {
    id: number;
    cover: string | null;
    title: string;
    author: {
      id: number;
      name: string;
      avatar: string | null;
      role: UserRole;
    };
    is_favorite: boolean;
  }[];
}


export function queryNovelListAllPrepare() {
  return async function queryNovelListAll(page: number) {
    try {
      const resp = await client.get<ApiResponse<NovelListResponse>>('/api/query/all', { params: { page } });
      return resp.data;
    } catch (error) {
      return fromError(error);
    }
  }
}

export function queryNovelListByTagPrepare(tag: string) {
  return async function queryNovelListByTag(page: number) {
    try {
      const resp = await client.get<ApiResponse<NovelListResponse>>('/api/query/by_tag', { params: { tag, page } });
      return resp.data;
    } catch (error) {
      return fromError(error);
    }
  }
}

export function getNovelListByAuthorPrepare(authorId: number) {
  return async function getNovelListByAuthor(page: number) {
    try {
      const resp = await client.get<ApiResponse<NovelListResponse>>('/api/query/by_author/' + authorId, { params: { page } });
      return resp.data;
    } catch (error) {
      return fromError(error);
    }
  }
}

export function queryNovelListByKeywordPrepare(keyword: string) {
  return async function queryNovelListByKeyword(page: number) {
    try {
      const resp = await client.get<ApiResponse<NovelListResponse>>('/api/query/by_keyword', { params: { keyword, page } });
      return resp.data;
    } catch (error) {
      return fromError(error);
    }
  }
}

export function queryNovelListByFavoritesPrepare() {
  return async function queryNovelListByFavorites(page: number) {
    try {
      const resp = await client.get<ApiResponse<NovelListResponse>>('/api/query/by_favorites', { params: { page } });
      return resp.data;
    } catch (error) {
      return fromError(error);
    }
  }
}

export type TagListResponse = {
  tags: {
    tag_name: string;
    count: number;
  }[];
}

export async function queryTags(keyword: string) {
  try {
    const resp = await client.get<ApiResponse<TagListResponse>>('/api/query/tags', { params: { keyword } });
    return resp.data;
  } catch (error) {
    return fromError(error);
  }
}
